package alg;

/**
编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀，返回空字符串 ""。
输入：strs = ["flower","flow","flight"]             输出："fl"
输入：strs = ["dog","racecar","car"]                输出：""
 */

public class LongestCommonPrefix {
    public static void main(String[] args) {
        String[] strs = {"123","12455"};
        System.out.println(lcp(strs));


    }

//    方法一

    public static String lcp(String[] strs){
        int len = strs.length;
        String result = strs[0];

        if (len==0 || len==1){
            return result;
        }else{
            for (int i = 1; i < strs.length; i++) {
                result = compareString(result,strs[i]);
            }
        }
        return result;
    }

    public static String compareString(String s1,String s2){
        String result = "";
        int len = (s1.length()<s2.length())?s1.length():s2.length();
        for (int i = 0; i < len; i++) {
            if (s1.charAt(i)==s2.charAt(i)){
                result += s1.charAt(i);
            }else {
                break;
            }
        }
        return result;
    }

}
